package com.xfcycle.zebrabikegp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.vise.baseble.callback.scan.IScanCallback;
import com.vise.baseble.model.BluetoothLeDevice;
import com.vise.baseble.model.BluetoothLeDeviceStore;
import com.xfcycle.zebrabikegp.R;
import com.xfcycle.zebrabikegp.assist.BlueToothAssist;
import com.xfcycle.zebrabikegp.bean.BikeInfoResult;
import com.xfcycle.zebrabikegp.constant.ToastConstant;
import com.xfcycle.zebrabikegp.util.HandleDataByBLEUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BluetoothSearchActivity extends RootActivity {
    private static final String TAG = "BluetoothSearch";
    private Gson gson = new Gson();

    private ImageView iv_search_bike_back;
    private RelativeLayout rl_search_bike_contain;

    private ImageView iv_search_bike_circle_01;
    private ImageView iv_search_bike_circle_02;
    private ImageView iv_search_bike_circle_03;
    private ImageView iv_search_bike_circle_04;

    private LinearLayout ll_search_container_01;
    private LinearLayout ll_search_container_02;
    private LinearLayout ll_search_container_03;
    private LinearLayout ll_search_container_04;
    private LinearLayout ll_search_container_05;
    private LinearLayout ll_search_container_06;
    private LinearLayout ll_search_container_07;
    private LinearLayout ll_search_container_08;

    private TextView tv_search_bike_name_01;
    private TextView tv_search_bike_name_02;
    private TextView tv_search_bike_name_03;
    private TextView tv_search_bike_name_04;
    private TextView tv_search_bike_name_05;
    private TextView tv_search_bike_name_06;
    private TextView tv_search_bike_name_07;
    private TextView tv_search_bike_name_08;

    private int screenWidth;
    private int scale_ratio;

    private String uid;

    private List<LinearLayout> containers;
    private List<TextView> bikeNameTVs;
    private int showIndex = 0;
    private Map<String, String> bikeInfos = new HashMap<>();

    private StringBuilder sbScanBikeName;

    private HandleDataByBLEUtil handleDataByBLEUtil;

    private Integer tvIndex = 0;

    private Handler delayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    rippleAnimation(iv_search_bike_circle_01);
                    break;
                case 1:
                    rippleAnimation(iv_search_bike_circle_02);
                    break;
                case 2:
                    rippleAnimation(iv_search_bike_circle_03);
                    break;
                case 3:
                    rippleAnimation(iv_search_bike_circle_04);
                    break;
                case 4:
                    containers.get(showIndex).setVisibility(View.VISIBLE);
                    break;
                case 5:
                    //开启搜索蓝牙设备
                    startScanAroundBike();
                    break;
            }
        }
    };

    private BikeInfoResult[] bikeInfoResults;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_search);

        bikeInfos = gson.fromJson(getIntent().getExtras().getString("bikeInfos"), bikeInfos.getClass());

        initView();
        initViewListener();

        delayHandler.sendEmptyMessageDelayed(0, 700);
        delayHandler.sendEmptyMessageDelayed(1, 1400);
        delayHandler.sendEmptyMessageDelayed(2, 2100);
        delayHandler.sendEmptyMessageDelayed(3, 2800);
        delayHandler.sendEmptyMessageDelayed(5, 3500);
    }

    @Override
    protected void onPause() {
        super.onPause();
        handleDataByBLEUtil.stopScanDevice();
        handleDataByBLEUtil.progress = null;
    }

    /**
     * 初始化组件
     */
    public void initView() {
        iv_search_bike_back = (ImageView) findViewById(R.id.iv_search_bike_back);
        rl_search_bike_contain = (RelativeLayout) findViewById(R.id.rl_search_bike_contain);

        iv_search_bike_circle_01 = (ImageView) findViewById(R.id.iv_search_bike_circle_01);
        iv_search_bike_circle_02 = (ImageView) findViewById(R.id.iv_search_bike_circle_02);
        iv_search_bike_circle_03 = (ImageView) findViewById(R.id.iv_search_bike_circle_03);
        iv_search_bike_circle_04 = (ImageView) findViewById(R.id.iv_search_bike_circle_04);

        ll_search_container_01 = (LinearLayout) findViewById(R.id.ll_search_container_01);
        ll_search_container_02 = (LinearLayout) findViewById(R.id.ll_search_container_02);
        ll_search_container_03 = (LinearLayout) findViewById(R.id.ll_search_container_03);
        ll_search_container_04 = (LinearLayout) findViewById(R.id.ll_search_container_04);
        ll_search_container_05 = (LinearLayout) findViewById(R.id.ll_search_container_05);
        ll_search_container_06 = (LinearLayout) findViewById(R.id.ll_search_container_06);
        ll_search_container_07 = (LinearLayout) findViewById(R.id.ll_search_container_07);
        ll_search_container_08 = (LinearLayout) findViewById(R.id.ll_search_container_08);

        tv_search_bike_name_01 = (TextView) findViewById(R.id.tv_search_bike_name_01);
        tv_search_bike_name_02 = (TextView) findViewById(R.id.tv_search_bike_name_02);
        tv_search_bike_name_03 = (TextView) findViewById(R.id.tv_search_bike_name_03);
        tv_search_bike_name_04 = (TextView) findViewById(R.id.tv_search_bike_name_04);
        tv_search_bike_name_05 = (TextView) findViewById(R.id.tv_search_bike_name_05);
        tv_search_bike_name_06 = (TextView) findViewById(R.id.tv_search_bike_name_06);
        tv_search_bike_name_07 = (TextView) findViewById(R.id.tv_search_bike_name_07);
        tv_search_bike_name_08 = (TextView) findViewById(R.id.tv_search_bike_name_08);

        containers = new ArrayList<>();
        containers.add(ll_search_container_01);
        containers.add(ll_search_container_02);
        containers.add(ll_search_container_03);
        containers.add(ll_search_container_04);
        containers.add(ll_search_container_05);
        containers.add(ll_search_container_06);
        containers.add(ll_search_container_07);
        containers.add(ll_search_container_08);

        bikeNameTVs = new ArrayList<>();
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);
        bikeNameTVs.add(tv_search_bike_name_01);

        handleDataByBLEUtil = HandleDataByBLEUtil.getInstance(this, -1);

        sbScanBikeName = new StringBuilder();

        //获得屏幕的分辨率
        float ppi = getResources().getDisplayMetrics().density;

        //获得屏幕的宽
        DisplayMetrics dm = getResources().getDisplayMetrics();
        screenWidth = dm.widthPixels;

        scale_ratio = screenWidth / (80 * (int) ppi);

        //查找用户的所有自行车
//        new GetJsonFromWebJob(WebConstant.GET_USER_BIKE_PATH_ONE + uid + WebConstant.GET_USER_BIKE_PATH_TWO, WebConstant.GET, null, REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO, BluetoothSearchActivity.this).start();
    }

    /**
     * 组件监听事件添加
     */
    public void initViewListener() {
        //回退按钮事件
        iv_search_bike_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                closeActivity();
            }
        });

        /**
         //搜索到附近设备
         handleDataByBLEUtil.setOnBluetoothScanFindDeviceListener(new BluetoothScanFindDeviceListener() {
        @Override public void findFuzzyDevices(List<BluetoothDevice> devices_list) {
        }

        @Override public void findFuzzyDevice(BluetoothDevice device) {

        Log.w(TAG, "findFuzzyDevice: ------------------- name:" + device.getName() + "---- address:" + device.getAddress());

        if (null == device) {
        return;
        }

        String bikeName;
        if (null == device.getName() || "".equals(device.getName())) {
        if (null == device.getAddress() || "".equals(device.getAddress())) {
        return;
        }
        bikeName = "vta_" + EncryptStringUtil.customBase64Encode(device.getAddress());
        } else {
        bikeName = device.getName();
        }

        //判断之前是否已经搜索到
        if (null != sbScanBikeName && sbScanBikeName.toString().contains(bikeName)) {
        return;
        }

        if (bikeInfos.size() <= 0) {
        return;
        }
        String bikeNickName = bikeInfos.get(bikeName);

        Log.w(TAG, "findFuzzyDevice: ----------- " + bikeInfos);
        //用户拥有搜索到的车子 显示车子图标 并展示名字
        if (null != bikeNickName && showIndex < 8) {
        containers.get(showIndex).setVisibility(View.VISIBLE);
        Log.w(TAG, "findFuzzyDevice: ----------------- bikeNickName" + bikeNickName + "---- bikeName" + bikeName);
        bikeNameTVs.get(showIndex).setText("#$%&**".equals(bikeNickName) ? bikeName : bikeNickName);
        bikeNameTVs.get(showIndex).setTag(bikeName);
        showIndex++;
        }

        //将已经搜索到的设备记录，防止重复展示
        sbScanBikeName.append(bikeName);
        }

        @Override public void findParticularDevice(BluetoothDevice device) {

        }
        });
         */

        ll_search_container_01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_01);
            }
        });

        ll_search_container_02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_02);
            }
        });

        ll_search_container_03.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_03);
            }
        });

        ll_search_container_04.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_04);
            }
        });

        ll_search_container_05.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_05);
            }
        });

        ll_search_container_06.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_06);
            }
        });

        ll_search_container_07.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_07);
            }
        });

        ll_search_container_08.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnData(tv_search_bike_name_08);
            }
        });

    }

    /**
     * 向跳转前页面返回数据 并关闭当前窗体
     *
     * @param v 目标tv
     */
    private void returnData(TextView v) {
        Bundle backBundle = new Bundle();
        backBundle.putString("search_bike_name", v.getTag().toString());
        backBundle.putString("search_bike_nick_name", v.getText().toString());
        setResult(RESULT_OK, new Intent().putExtras(backBundle));
        finish();
    }

    /**
     * 水波纹动画
     *
     * @param view 需要添加动画效果的组件
     */
    private void rippleAnimation(final View view) {
        AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.0f);
        ScaleAnimation scaleAnimation = new ScaleAnimation(1.0f, scale_ratio, 1.0f, scale_ratio, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        final AnimationSet ripple = new AnimationSet(true);
        ripple.setDuration(3000);
        ripple.addAnimation(alphaAnimation);
        ripple.addAnimation(scaleAnimation);

        ripple.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.clearAnimation();
                view.startAnimation(ripple);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });

        view.startAnimation(ripple);
    }

    /**
     * 开启蓝牙广域搜索 搜索附近的车辆
     */
    private void startScanAroundBike() {
        //重置展示搜索到的设备组件下标
        tvIndex = 0;

        //判断设备是否支持蓝牙
        if (!handleDataByBLEUtil.judgeDeviceSupportBle()) {
            Toast.makeText(this.getApplicationContext(), ToastConstant.DEVICE_NOT_SUPPORT_BLE, Toast.LENGTH_LONG).show();
        }
        //开启蓝牙
        handleDataByBLEUtil.startBluetooth();
        //开启搜索
        handleDataByBLEUtil.scanDevices(new IScanCallback() {
            @Override
            public void onDeviceFound(BluetoothLeDeviceStore bluetoothLeDeviceStore) {
                refreshDeviceInfo(bluetoothLeDeviceStore.getDeviceList());
            }

            @Override
            public void onScanFinish(BluetoothLeDeviceStore bluetoothLeDeviceStore) {

            }

            @Override
            public void onScanTimeout() {

            }
        });
    }

    /**
     * 更新搜索到的车辆信息
     *
     * @param deviceList
     */
    private void refreshDeviceInfo(List<BluetoothLeDevice> deviceList) {
        Integer tvIndex = 0;

        for (int index = 0; index < deviceList.size(); index++) {
            String bikeName = deviceList.get(index).getName();
            //确定当前车辆为用户名下车辆
            String bikeNickName = bikeInfos.get(bikeName);
            //用户拥有搜索到的车子 显示车子图标 并展示名字
//            if (null != bikeNickName && index < 8 && bikeName.contains("vt")) {
            if (null != bikeNickName && index < 8) {
                containers.get(tvIndex).setVisibility(View.VISIBLE);
                bikeNameTVs.get(tvIndex).setText("#$%&**".equals(bikeNickName) ? bikeName : bikeNickName);
                bikeNameTVs.get(tvIndex).setTag(bikeName);

                tvIndex++;
            }
        }
    }
    /********************************************************************************************/
    /**                             处理从不同途径获得的数据                                       */
    /********************************************************************************************/
    /**
     * 处理从网络获得的数据
     *
     * @param webMsg
     */
    @Override
    public void dealDataFromWeb(Message webMsg) {
        super.dealDataFromWeb(webMsg);

        Gson gson = new Gson();
        String webResult = webMsg.obj.toString();
        int webSign = webMsg.what;

        Log.e(TAG, "dealDataFromWeb: -----------" + webResult);

        //判断登陆账号名下是否有车
        if (REQUEST_SIGN_HOME_MAP_GET_USER_BIKE_INFO == webSign && !"".equals(webResult)) {
            bikeInfoResults = gson.fromJson(webResult, BikeInfoResult[].class);

            if (bikeInfoResults.length <= 0) {
                Log.e(TAG, "dealDataFromWeb: ----------------------- 名下没有任何车辆");
            } else {
                //如果有车，取到车的信息,展示
                for (BikeInfoResult bikeInfoResult : bikeInfoResults) {
                    bikeInfos.put(bikeInfoResult.getName(), null == bikeInfoResult.getNickname() ? "#$%&**" : bikeInfoResult.getNickname());
                }
            }
            return;
        }

        //判断在其他设备登陆
        if (webMsg.obj.toString().contains("you are signed in at another location") && REQUEST_SIGN_LOGOUT != webMsg.what) {
            //断开连接
            HandleDataByBLEUtil.disConnectDevice();
            //改变蓝牙辅助判断类的值
            BlueToothAssist.isConnect = false;
            BlueToothAssist.currentConnectBikeId = null;

            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(ToastConstant.DIALOG_WARNING);
                builder.setMessage(ToastConstant.OTHER_DEVICE_LOGIN);

                builder.setPositiveButton(ToastConstant.DIALOG_I_KNOW, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //回到登录界面
                        activityChange(LOGIN_ACTIVITY, null, null);
                        HandleDataByBLEUtil.disConnectDevice();
                    }

                });
                //展示提示框
                builder.create().show();
            } catch (Exception e) {
                Toast.makeText(this.getApplicationContext(), ToastConstant.OTHER_DEVICE_LOGIN, Toast.LENGTH_LONG).show();
                activityChange(LOGIN_ACTIVITY, null, null);
                HandleDataByBLEUtil.disConnectDevice();
            }
        }
    }
}
